package com.hotec.PROJECT_NAME.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gemcap.framework.data.entity.TreeAble;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author
 */
public class UtilsTreeBuilder<T extends TreeAble> {

    protected Class<T> entityClass;

    public UtilsTreeBuilder(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public List<T> listToTree(List<T> data) {
        return listToTree(data, "id", "parentId", "children");
    }

    public List<T> listToTree(List<T> data, String id, String pid, String child) {
        if (CollectionUtils.isEmpty(data)) {
            return Lists.newArrayList();
        }
        JSONArray arr = JSONArray.parseArray(JSON.toJSONString(data));
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式，key为数组中的id
        for (int i = 0; i < arr.size(); i++) {
            JSONObject json = (JSONObject) arr.get(i);
            hash.put(json.getString(id), json);
        }
        //遍历结果集
        for (int j = 0; j < arr.size(); j++) {
            //单条记录
            JSONObject aVal = (JSONObject) arr.get(j);
            //在hash中取出key为单条记录中pid的值
            Object o = aVal.get(pid);
            if (Objects.isNull(o)) continue;
            JSONObject hashVP = (JSONObject) hash.get(o.toString());
            //如果记录的pid存在，则说明它有父节点，将她添加到孩子节点的集合中
            if (hashVP != null) {
                //检查是否有child属性
                if (hashVP.get(child) != null) {
                    JSONArray ch = (JSONArray) hashVP.get(child);
                    ch.add(aVal);
                    hashVP.put(child, ch);
                } else {
                    JSONArray ch = new JSONArray();
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }
            } else {
                r.add(aVal);
            }
        }
        return JSONArray.parseArray(JSON.toJSONString(r), entityClass);
    }
}
